var actions = {};

(function(){
	
	var response;
	
	var setUserAttrToUniqueRandomValue = function(userData, attribute, length){
		do{
			userData[attribute] = RandomString.gen(length);
			var searchObj = {};
			searchObj[attribute] = userData[attribute];
		}while(storage.users.getSingle(searchObj));
	};
	
	var setLoginCookie = function(cookieValue, redirectPath){
		response.setCookie({
			name: constants.get("loginCookieKey"), 
			path: "/",
			value: cookieValue, 
			expires: new Date().addYears(4)
		});
		
	}
	
	actions.toString = function(){return "[Actions Modules]";}
	
	actions.init = function(r){
		response = r;
	}
		
	actions.makeAnchorProcess = function(form, user, anchor){
		
		if(form.pass){
			
			anchor.owner = user.username;
			anchor.created = new Date();
			anchor.href = form.data.href;
			anchor.status = constants.get("anchorPendingStatus");
			
			var anchorId = storage.anchors.insert(anchor);
			
			anchor.id = (anchorId !== null)
        ? anchorId
        : form.serErrorMessage("Something went wrong.");
  	}
	}
	
	actions.editAnchorProcess = function(form, anchorId, anchor){
				
		if(form.pass){
		  anchor.href = form.data.href;
			anchor.edited = new Date();
			
			var anchorId = storage.anchors.updateById(anchorId, anchor);
			
			anchor.id = (anchorId !== null)
			  ?	anchorId
			  : form.serErrorMessage("Something went wrong.");
		}
	}
	
	
	actions.loginProcess = function(form){
		
		if(form.pass){
			var unconfirmedUser = form.data;
			var user = storage.users.getById(unconfirmedUser.username);
			
			if(user && (user.password == unconfirmedUser.password)){
				user.lastLogin = new Date();
				if(!user.cookie)
				  setUserAttrToUniqueRandomValue(user, "cookie", 8);
				storage.users.updateById(user.username, user);
				setLoginCookie(user.cookie);
			} else {
				form.setErrorMessage("Bad login.");
			}
		}
	}
	
	actions.registerProcess = function(form){
	
		if(form.pass){
			var newUser = form.data;
			newUser.created = newUser.lastLogin = new Date();
			setUserAttrToUniqueRandomValue(newUser, "publisherId", 12);
			setUserAttrToUniqueRandomValue(newUser, "cookie", 8);
			
			(storage.users.insert(newUser) !== null)
				? setLoginCookie(newUser.cookie)
			  : form.setErrorMessage("Username already in use.");
			
		}
	}
	
	
})();
